﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    public class LoginController : Controller
    {
        private readonly AdminUserService _adminUserService;
        private readonly NoticeKeyService _notice;
        private readonly LogService _logService;
        public LoginController(AdminUserService adminUserService, NoticeKeyService noticeService, LogService logService)
        {
            _adminUserService = adminUserService;
            _logService = logService;
            _notice = noticeService;
        }

        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> IndexAsync()
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            if (result.Succeeded)
                return Redirect("/Admin/Home");
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(string username, string password)
        {
            string ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
            if (username == null || password == null)
                return Json(new { status = 0, msg = "用户名密码不能为空！" });
            string md5Password = MD5Utility.MD5Encrypt32(password).ToLower();
            var loginInfo = await _adminUserService.CheckUorP(username, md5Password);
            if (loginInfo != null)
            {
                //将用户信息写入COOKIES
                var claims = new List<Claim>
                    {
                        new Claim("id", loginInfo.Id.ToString()),
                        new Claim("gid", loginInfo.Gid.ToString()),
                        new Claim("username", loginInfo.Username),
                        new Claim("nickname", loginInfo.Nickname),
                        new Claim("loginip",ip),
                        new Claim("logintime", loginInfo.Logintime.ToString()),
                    };

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(new ClaimsIdentity(claims, "CxuuWebCore")),
                    new AuthenticationProperties
                    {
                        ExpiresUtc = DateTime.UtcNow.AddDays(7),
                        IsPersistent = true,//在浏览器持久化，false的时候走session持久化
                        AllowRefresh = true//动态刷新令牌
                    }
                    );

                //更新登录信息
                EditAdminUser currentUser = new()
                {
                    Loginip = ip,
                    Logintime = DateTime.Now,
                };
                await _adminUserService.UpdateLoginInfoAsync(currentUser, loginInfo.Id);

                //发送通知
                EditNotice notice = new()
                {
                    GetUid = loginInfo.Id.ToString(),
                    Title = "欢迎登录",
                    PostTime = DateTime.Now,
                    Content = "欢迎您登录，亲爱的 " + loginInfo.Nickname + " ,祝您一切美好！",
                };
                await _notice.InsertAsync(notice);
                //操作日志
                UserInfo userInfo = new()
                {
                    Id = loginInfo.Id,
                    Action = "login",
                    Controller = "login",
                    Ip = ip,
                };
                await _logService.InsertLogSqlAsync(userInfo, "后台登录");


                return Json(new { status = 1, msg = "登录成功！" });
            }
            else
                return Json(new { status = 1, msg = "用户名密码错误！", url = "/Admin" });
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> LoginOut()
        {
            await HttpContext.SignOutAsync();
            return Redirect("/Admin/Login");
        }

    }
}
